package com.boot2.core.mqtt;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.converter.MessageConversionException;

/**
 * @author zhangweilin
 * @description: 默认的mqtt消息发送，只能发送String和byte[]，现扩展，能发送任意类型，如果是对象类型，自动转成json
 * @date 2018/9/30
 */
public class HlPahoMessageConverter extends DefaultPahoMessageConverter {

    @Override
    protected byte[] messageToMqttBytes(Message<?> message) {
        Object payload = message.getPayload();
        byte[] payloadBytes;
        if (!(payload instanceof byte[] || payload instanceof String)) {
            String json = JSONObject.toJSONString(payload, SerializerFeature.WriteDateUseDateFormat);
            try {
                payloadBytes = json.getBytes("UTF-8");
                return payloadBytes;
            }
            catch (Exception e) {
                throw new MessageConversionException("failed to convert Message to object", e);
            }
        }

        if (payload instanceof String) {
            try {
                payloadBytes = ((String) payload).getBytes("UTF-8");
            }
            catch (Exception e) {
                throw new MessageConversionException("failed to convert Message to object", e);
            }
        }
        else {
            payloadBytes = (byte[]) payload;
        }
        return payloadBytes;
    }
}
